package 设计模式.责任链模式;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import 设计模式.责任链模式.filter.Filter;

import com.jweb.util.ClassUtil;

public class FilterChain<T> extends Filter<T> {

	private List<Filter<T>> listfilter = new ArrayList<Filter<T>>();

	private AtomicInteger aint = new AtomicInteger(-1);

	@SuppressWarnings("unchecked")
	public FilterChain() {
		try {
			Set<Class<?>> sets = new ClassUtil<Class<?>>().getClasses(getClass().getPackage().getName(), ".class");
			for (Class<?> cla : sets) {
				if (cla.getSuperclass() == Filter.class && cla != this.getClass())
					listfilter.add((Filter<T>) cla.newInstance());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			init();
		}
	}

	public void init() {
		aint.set(-1);
		System.err.println("===init succ");
	}

	public void doFilter(T t, FilterChain<T> filterChain) {
		int i = aint.addAndGet(1);
		System.out.println(i);
		if (i < listfilter.size())
			listfilter.get(i).doFilter(t, filterChain);
	}

	public void destory() {
		System.err.println("===destory succ");

	}

}
